﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using OutdoorLib.BaseEntity.Face;
using OutdoorLib.WS;
using OutdoorLib.BaseEntity.Agency;
using OutdoorLib.BaseEntity.Filters;
using OutdoorLib.BaseEntity.WS;
using Grishko.Tools;
using Grishko.DataTier;

public partial class EmployeeEditor : MasterPage_EditControl
{
    
    protected void Page_Load(object sender, EventArgs e)
    {   
        if (!this.IsPostBack)
            MyDataBind();

        SetAlertForTextBox();
    }


    

    protected  Employeer CtlLoginEditor_EmplSource()
    {
        return Employeer;
    }

    private void MyDataBind()
    {
        
        chRoleList.Items.Clear();
        chRoleList.Items.AddRange(AppEnvironment .Securety .GetRoles (Employeer .Login).ToArray<ListItem>());
        lvLogin.DataSource = EmployeerAsList;
        DataBind();
        
    }

    private List<Employeer> EmployeerAsList
    { 
        get{
            List<Employeer> res = new List<Employeer>();
            res.Add(Employeer);
            return res;
        }

    }


    protected  bool ImSavedObject
    {
        get { return !GlobalConstants.IsNewRecord(CurrentID); } 
    }

    //private string CurrentID
    //{
    //    get 
    //    {   

    //        return Request.QueryString[GlobalConstants.qID];
    //    }
        
    //}

    //private string CurrentTagName
    //{
    //    get { return Request.QueryString[GlobalConstants.qTagName]; }
    //}

    private Department  CurrentDepartment
    {
        get         
        {
            string s= Request.QueryString[EmployeeListFilter.qDepartmentID];
            if (string.IsNullOrEmpty(s)) 
                            return null;
            return AppEnvironment.CurrentAgency.GetDepartment(s);


        }
    }

    

    /// <summary>
    /// Редактируем текущего пользователя?
    /// </summary>
    protected bool IsCurrentUser
    {
        get { return AppEnvironment.CurrentEmployeer.ID == Employeer.ID; }
    }


    private Employeer _Employeer = null;
    protected  Employeer Employeer
    {
        get
        {
            if (null != _Employeer)
                return _Employeer;

            if (GlobalConstants.IsNewRecord(CurrentID))
                _Employeer=(Employeer)AppEnvironment.ObjectFactory.GetNewObject(CurrentTagName, GlobalConstants.GetNewID (CurrentID));
            else
                _Employeer=(Employeer)AppEnvironment.ObjectFactory.GetObject(CurrentID, CurrentTagName);

            return _Employeer;
        }

    }

    private bool Save()
    {
        List <string > err= AppEnvironment.BusinessRules.CheckUpdate(Employeer);
        if (err.Count > 0)
        {
            AppEnvironment.Helper.RegistredStartUpAlert(this, err);
            return false;
        }
        //Указан ли ссотвю департамент
        if (null == CurrentDepartment)
            throw new Exception("Департамент с  не найден.");
        try
        {
            // Если эта новая запись - id убрать префикс новой записи
            if (GlobalConstants.IsNewRecord(Employeer.ID))
                Employeer.ID = CurrentID;
            
            // добавить сотрудника в агентсво
            CurrentDepartment.Employees.Remove(CurrentID);
            CurrentDepartment.Employees.Add(Employeer);
            //сохранить агентсво с эсколацией save - в результате сохраниться все вход. бъекты
            wsAgency.SaveAgency();
            
            // почистить кэш 
            AppEnvironment.ObjectFactory.ResetCashe(GlobalConstants.GetNewID(CurrentID));
            
            SetRoles();

            return true;
        }
        catch
        {
            return false;
        }
    }

    protected string LoginErrMsg
    { get {return  "Информация о ошибке "; } }


    private void ReadForm()    
    {
        Employeer.FirstName = txtFirstName.Text ;
        Employeer.SecondName = txtSecondName.Text;
        Employeer.LastName = txtLastName.Text;
        Employeer.Position = txtPosition.Text;
        Employeer.Comment = txtComment.Text;
        Employeer .eMail =txtEmail .Text;
        

    }

    protected void btnSaveExit_Click(object sender, EventArgs e)
    {
        ReadForm();
        if (!Save())
                return;

        QueryStringTools.RefreshPageWitchReturnUrl();
    }
    protected void btnsave_Click(object sender, EventArgs e)
    {   
        bool bRedirect=GlobalConstants.IsNewRecord ( CurrentID);
        ReadForm();
        if (!Save())
            return;

        if (bRedirect)
            QueryStringTools.RefreshPage(GlobalConstants.qID + "=" + Employeer.ID);
        
        HideAlert();
    }

    

    private void SetRoles()
    {
        if (Employeer.Login == string.Empty)
            return;

        List<string> list = new List<string>();
        foreach (ListItem i in chRoleList.Items )
        {
            if (i.Selected)
                    list.Add(i.Value );
        }
            AppEnvironment.Securety.SetUserRoles(Employeer.Login, list.ToArray<string>());
    }

    private bool UpdateLogin(ListViewDataItem sender)
    {
        TextBox log = (TextBox)lvLogin.EditItem.FindControl("txtLogin");
        TextBox pass = (TextBox)lvLogin.EditItem.FindControl("txtPassword");
        Label errMsg = (Label)lvLogin.EditItem.FindControl("errMsg");
        string ErrRes = AppEnvironment.Securety.CreateUser(log.Text , pass.Text );
        if (ErrRes.Length == 0)
        {
            Employeer.Login = log.Text;
            Save();
            return true;
        }
        errMsg.Text = ErrRes;
        return false;
    }

    

    protected List<Employeer> EmploeerAsList
    {
        get
        {
            List<Employeer> l = new List<Employeer>();
            l.Add(Employeer);
            return l;
        }
    }


    Func<ListViewDataItem, bool> LvUpdCmd;
    
    protected void ItemCommand(object sender, ListViewCommandEventArgs e)
    {
        if (string.Empty == e.CommandName) return;

        ListView lv = (ListView)sender;

        switch (lv.ID)
        {
            case "lvLogin":
                LvUpdCmd = UpdateLogin;
                break;

        }
        int CurrLvIdx = lv.EditIndex;
        switch (e.CommandName)
        {
            case "Edit":
                {

                    ListViewDataItem d = (ListViewDataItem)e.Item;
                    lv.EditIndex = d.DataItemIndex;                    

                    break;
                }
            case "Insert":
                {

                    break;
                }
            case "Update":
                {
                    if (LvUpdCmd((ListViewDataItem)e.Item))                    
                        lv.EditIndex = -1;
                    


                    break;
                }
            case "Delete":
                {
                    //DeleteCustomer(e.CommandArgument as string);
                    break;
                }

            case "Cancel":
                {

                    break;
                }
        }

        if (CurrLvIdx != lv.EditIndex)
        {
            lv.DataSource = EmploeerAsList;
            MyDataBind ();
        }

        
        //chRoleList.DataBind();
        //updLoginInfo.Update();
        //SetAlertForTextBox(this.Controls, "TextBox", "onChange", "ShowAlert()");
        //SetMsg_EditStatus();



    }

    

    
    protected void lvLogin_ItemEditing(object sender, ListViewEditEventArgs e)
    {
        
    }
    
    protected void lvLogin_ItemUpdating(object sender, ListViewUpdateEventArgs e)
    {

    }
    
    protected void lvLogin_ItemCanceling(object sender, ListViewCancelEventArgs e)
    {
        ((ListView)sender).EditIndex = -1;
        ((ListView)sender).DataSource = EmploeerAsList;
        ((ListView)sender).DataBind();
    }

}
